<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 主要内容 -->
    <view class="main-content">
      <!-- Logo区域 -->
      <view class="logo-section">
        <view class="logo-wrapper">
          <image class="logo-image" :src="globalConfig.appInfo.logo" mode="aspectFit"></image>
        </view>
        <text class="app-title">{{ globalConfig.appInfo.name }}</text>
        <text class="app-subtitle">欢迎回来，请登录您的账户</text>
      </view>

      <!-- 登录表单 -->
      <view class="form-card">
        <view class="form-header">
          <text class="form-title">账户登录</text>
          <text class="form-subtitle">请输入您的登录信息</text>
        </view>

        <view class="form-content">
          <!-- 用户名输入 -->
          <view class="input-group">
            <view class="input-wrapper">
              <view class="input-icon">
                <uni-icons type="person" size="20" color="#007aff"></uni-icons>
              </view>
              <input 
                v-model="loginForm.username" 
                class="form-input" 
                type="text" 
                placeholder="请输入用户名" 
                maxlength="30"
                :focus="false"
              />
            </view>
          </view>

          <!-- 密码输入 -->
          <view class="input-group">
            <view class="input-wrapper">
              <view class="input-icon">
                <uni-icons type="locked" size="20" color="#007aff"></uni-icons>
              </view>
              <input 
                v-model="loginForm.password" 
                type="password" 
                class="form-input" 
                placeholder="请输入密码" 
                maxlength="20"
                :focus="false"
              />
            </view>
          </view>

          <!-- 验证码输入 -->
          <view class="input-group" v-if="captchaEnabled">
            <view class="input-wrapper captcha-wrapper">
              <view class="input-icon">
                <uni-icons type="chatboxes" size="20" color="#007aff"></uni-icons>
              </view>
              <input 
                v-model="loginForm.code" 
                type="number" 
                class="form-input captcha-input" 
                placeholder="请输入验证码" 
                maxlength="4"
                :focus="false"
              />
              <view class="captcha-image-wrapper" @click="getCode">
                <image :src="codeUrl" class="captcha-image" mode="aspectFit"></image>
                <view class="captcha-refresh">
                  <uni-icons type="refresh" size="16" color="#007aff"></uni-icons>
                </view>
              </view>
            </view>
          </view>

          <!-- 登录按钮组 -->
          <view class="button-group">
            <!-- 账号密码登录按钮 -->
            <button 
              @click="handleLogin" 
              class="login-button" 
              :disabled="isLoggingIn"
              :loading="isLoggingIn"
            >
              <text v-if="!isLoggingIn">立即登录</text>
              <text v-else>登录中...</text>
            </button>
            
            <!-- #ifdef MP-WEIXIN -->
            <button 
              @click="handleWechatMiniLogin" 
              class="wechat-login-button"
              :disabled="isWechatLoggingIn"
            >
              <view class="wechat-icon">
                <uni-icons type="weixin" size="24" color="#ffffff"></uni-icons>
              </view>
              <text>微信一键登录</text>
            </button>
            <!-- #endif -->
          </view>

          <!-- 其他选项 -->
          <view class="options-section">
            <view class="register-link">
              <text class="link-text">还没有账户？</text>
              <text @click="handleUserRegister" class="link-button">立即注册</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 协议区域 -->
      <view class="agreement-section">
        <text class="agreement-text">登录即代表同意</text>
        <text @click="handleUserAgrement" class="agreement-link">《用户协议》</text>
        <text class="agreement-text">和</text>
        <text @click="handlePrivacy" class="agreement-link">《隐私政策》</text>
      </view>
    </view>

    <!-- 微信绑定弹窗 -->
    <uni-popup ref="bindPopup" type="center" :mask-click="false">
      <view class="bind-popup">
        <view class="bind-popup-header">
          <text class="bind-popup-title">绑定账号</text>
          <text class="bind-popup-subtitle">请输入手机号绑定微信账号</text>
        </view>
        
        <view class="bind-popup-content">
          <!-- 微信用户信息展示 -->
          <view class="wechat-user-info" v-if="wechatUserInfo">
            <image :src="wechatUserInfo.headimgurl" class="wechat-avatar" mode="aspectFill"></image>
            <text class="wechat-nickname">{{ wechatUserInfo.nickname }}</text>
          </view>
          
          <!-- 手机号输入 -->
          <view class="bind-input-group">
            <view class="bind-input-wrapper">
              <view class="bind-input-icon">
                <uni-icons type="phone" size="20" color="#007aff"></uni-icons>
              </view>
              <input 
                v-model="bindForm.phoneNumber" 
                class="bind-input" 
                type="number" 
                placeholder="请输入手机号" 
                maxlength="11"
              />
            </view>
          </view>
          
          <!-- 按钮组 -->
          <view class="bind-button-group">
            <button 
              @click="closeBind" 
              class="bind-cancel-button"
            >
              取消
            </button>
            <button 
              @click="handleBind" 
              class="bind-confirm-button"
              :disabled="isBinding"
            >
              <text v-if="!isBinding">确认绑定</text>
              <text v-else>绑定中...</text>
            </button>
          </view>
        </view>
      </view>
    </uni-popup>

    <!-- 解绑确认弹窗 -->
    <uni-popup ref="unbindPopup" type="center" :mask-click="false">
      <view class="unbind-popup">
        <view class="unbind-popup-header">
          <text class="unbind-popup-title">解绑确认</text>
        </view>
        
        <view class="unbind-popup-content">
          <text class="unbind-message">该手机号已绑定其他微信账号，是否解绑并重新绑定？</text>
          
          <view class="unbind-button-group">
            <button 
              @click="closeUnbind" 
              class="unbind-cancel-button"
            >
              取消
            </button>
            <button 
              @click="handleForceRebind" 
              class="unbind-confirm-button"
              :disabled="isBinding"
            >
              <text v-if="!isBinding">确认解绑</text>
              <text v-else>处理中...</text>
            </button>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue"
import { onLoad } from "@dcloudio/uni-app"
import { getToken } from '@/utils/auth'
import { getCodeImg, wechatMiniLogin, bindWechatAccount, forceRebindWechat } from '@/api/login'
import { useConfigStore, useUserStore } from '@/store'

const { proxy } = getCurrentInstance()
const globalConfig = useConfigStore().config
const codeUrl = ref("")
const isLoggingIn = ref(false)

// 验证码开关
const captchaEnabled = ref(true)
const loginForm = ref({
  username: "admin",
  password: "admin123",
  code: "",
  uuid: ""
})

// 微信登录相关
const isWechatLoggingIn = ref(false)
const isBinding = ref(false)
const wechatUserInfo = ref(null)
const bindForm = ref({
  phoneNumber: ""
})

// 用户注册
function handleUserRegister() {
  proxy.$tab.redirectTo(`/pages/register`)
}

// 隐私协议
function handlePrivacy() {
  let site = globalConfig.appInfo.agreements[0]
  proxy.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
}

// 用户协议
function handleUserAgrement() {
  let site = globalConfig.appInfo.agreements[1]
  proxy.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
}

// 获取图形验证码
function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      loginForm.value.uuid = res.uuid
    }
  })
}

// 登录方法
async function handleLogin() {
  if (loginForm.value.username === "") {
    proxy.$modal.msgError("请输入用户名")
    return
  }
  if (loginForm.value.password === "") {
    proxy.$modal.msgError("请输入密码")
    return
  }
  if (loginForm.value.code === "" && captchaEnabled.value) {
    proxy.$modal.msgError("请输入验证码")
    return
  }

  isLoggingIn.value = true
  proxy.$modal.loading("登录中，请稍候...")
  
  try {
    await pwdLogin()
  } catch (error) {
    isLoggingIn.value = false
    if (captchaEnabled.value) {
      getCode()
    }
  }
}

// 密码登录
async function pwdLogin() {
  try {
    await useUserStore().login(loginForm.value)
    proxy.$modal.closeLoading()
    await loginSuccess()
  } catch (error) {
    proxy.$modal.closeLoading()
    throw error
  }
}

// 登录成功后，处理函数
async function loginSuccess() {
  try {
    const userStore = useUserStore()
    // 同时获取用户信息和路由信息
    await userStore.refreshUserInfo()
    proxy.$tab.reLaunch('/pages/index')
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 登录成功但获取用户信息失败，仍然跳转到首页
    proxy.$tab.reLaunch('/pages/index')
  }
}

// 微信小程序登录
async function handleWechatMiniLogin() {
  // #ifdef MP-WEIXIN
  isWechatLoggingIn.value = true
  proxy.$modal.loading("微信登录中...")
  
  try {
    // 获取微信授权
    const loginRes = await new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          console.error('微信登录失败:', err)
          reject(err)
        }
      })
    })
    
    if (loginRes.code) {
      // 调用后端微信小程序登录接口
      await handleWechatMiniLoginCallback(loginRes.code)
    } else {
      throw new Error('获取微信授权失败')
    }
  } catch (error) {
    console.error('微信小程序登录失败:', error)
    proxy.$modal.closeLoading()
    proxy.$modal.msgError('微信登录失败，请稍后重试')
    isWechatLoggingIn.value = false
  }
  // #endif
}

// 处理微信小程序登录回调
async function handleWechatMiniLoginCallback(code) {
  try {
    const result = await wechatMiniLogin(code)
    
    if (result.token) {
      // 登录成功，保存token
      const userStore = useUserStore()
      userStore.SET_TOKEN(result.token)
      proxy.$modal.closeLoading()
      await loginSuccess()
    } else if (result.needBind && result.wechatUser) {
      // 需要绑定账号
      proxy.$modal.closeLoading()
      wechatUserInfo.value = result.wechatUser
      proxy.$refs.bindPopup.open()
    } else {
      // 其他情况
      proxy.$modal.closeLoading()
      proxy.$modal.msgError('微信登录状态异常')
    }
    
    isWechatLoggingIn.value = false
  } catch (error) {
    console.error('微信小程序登录回调处理失败:', error)
    proxy.$modal.closeLoading()
    
    // 检查是否是需要绑定账号的情况（兼容旧版本）
    if (error.needBind && error.wechatUser) {
      // 需要绑定账号
      wechatUserInfo.value = error.wechatUser
      proxy.$refs.bindPopup.open()
    } else {
      // 其他错误
      proxy.$modal.msgError(error.msg || '微信登录失败')
    }
    
    isWechatLoggingIn.value = false
  }
}

// 绑定账号
async function handleBind() {
  if (!bindForm.value.phoneNumber) {
    proxy.$modal.msgError('请输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(bindForm.value.phoneNumber)) {
    proxy.$modal.msgError('请输入正确的手机号')
    return
  }
  
  isBinding.value = true
  proxy.$modal.loading("绑定中...")
  
  try {
    const result = await bindWechatAccount(wechatUserInfo.value.openid, bindForm.value.phoneNumber)
    
    if (result.token) {
      // 绑定成功，保存token
      const userStore = useUserStore()
      userStore.SET_TOKEN(result.token)
      proxy.$modal.closeLoading()
      proxy.$refs.bindPopup.close()
      
      try {
        await loginSuccess()
        proxy.$modal.msgSuccess('绑定成功')
      } catch (loginError) {
        console.error('获取用户信息失败:', loginError)
        // 即使用户信息获取失败，绑定也已成功，直接跳转
        proxy.$tab.reLaunch('/pages/index')
        proxy.$modal.msgSuccess('绑定成功')
      }
    } else {
      proxy.$modal.closeLoading()
      proxy.$modal.msgError('绑定返回数据异常')
    }
  } catch (error) {
    proxy.$modal.closeLoading()
    
    if (error.msg === 'NEED_UNBIND') {
      // 需要解绑
      proxy.$refs.bindPopup.close()
      proxy.$refs.unbindPopup.open()
    } else {
      proxy.$modal.msgError(error.msg || '绑定失败')
    }
  }
  
  isBinding.value = false
}

// 强制解绑并重新绑定
async function handleForceRebind() {
  isBinding.value = true
  proxy.$modal.loading("处理中...")
  
  try {
    const result = await forceRebindWechat(wechatUserInfo.value.openid, bindForm.value.phoneNumber, true)
    
    if (result.token) {
      // 绑定成功，保存token
      const userStore = useUserStore()
      userStore.SET_TOKEN(result.token)
      proxy.$modal.closeLoading()
      proxy.$refs.unbindPopup.close()
      await loginSuccess()
    }
  } catch (error) {
    proxy.$modal.closeLoading()
    proxy.$modal.msgError(error.msg || '操作失败')
  }
  
  isBinding.value = false
}

// 关闭绑定弹窗
function closeBind() {
  proxy.$refs.bindPopup.close()
  bindForm.value.phoneNumber = ""
  wechatUserInfo.value = null
}

// 关闭解绑弹窗
function closeUnbind() {
  proxy.$refs.unbindPopup.close()
}

onLoad((options) => {
  //#ifdef H5
  if (getToken()) {
    proxy.$tab.reLaunch('/pages/index')
    return
  }
  //#endif
})

getCode()
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  
  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    
    &.circle-1 {
      width: 200rpx;
      height: 200rpx;
      top: -100rpx;
      right: -100rpx;
    }
    
    &.circle-2 {
      width: 300rpx;
      height: 300rpx;
      bottom: -150rpx;
      left: -150rpx;
    }
    
    &.circle-3 {
      width: 150rpx;
      height: 150rpx;
      top: 50%;
      right: 10%;
    }
  }
}

.main-content {
  position: relative;
  z-index: 1;
  padding: 40rpx;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.logo-section {
  text-align: center;
  margin-bottom: 60rpx;
  
  .logo-wrapper {
    margin-bottom: 30rpx;
    
    .logo-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 24rpx;
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
    }
  }
  
  .app-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #ffffff;
    margin-bottom: 16rpx;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  }
  
  .app-subtitle {
    display: block;
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
    line-height: 1.5;
  }
}

.form-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20rpx);
  border-radius: 32rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 40rpx;
  
  .form-header {
    text-align: center;
    margin-bottom: 50rpx;
    
    .form-title {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 12rpx;
    }
    
    .form-subtitle {
      display: block;
      font-size: 26rpx;
      color: #666666;
    }
  }
  
  .form-content {
    .input-group {
      margin-bottom: 32rpx;
      
      .input-wrapper {
        position: relative;
        background: #f8f9fa;
        border-radius: 20rpx;
        border: 2rpx solid transparent;
        transition: all 0.3s ease;
        
        &:focus-within {
          background: #ffffff;
          border-color: #007aff;
          box-shadow: 0 0 0 6rpx rgba(0, 122, 255, 0.1);
        }
        
        .input-icon {
          position: absolute;
          left: 24rpx;
          top: 50%;
          transform: translateY(-50%);
          z-index: 1;
        }
        
        .form-input {
          width: 100%;
          height: 88rpx;
          padding: 0 24rpx 0 72rpx;
          font-size: 28rpx;
          color: #333333;
          background: transparent;
          border: none;
          outline: none;
          
          &::placeholder {
            color: #999999;
          }
        }
        
        &.captcha-wrapper {
          display: flex;
          align-items: center;
          
          .captcha-input {
            flex: 1;
            padding-right: 24rpx;
          }
          
          .captcha-image-wrapper {
            position: relative;
            width: 180rpx;
            height: 60rpx;
            margin-left: 20rpx;
            border-radius: 12rpx;
            overflow: hidden;
            cursor: pointer;
            
            .captcha-image {
              width: 100%;
              height: 100%;
            }
            
            .captcha-refresh {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              background: rgba(255, 255, 255, 0.9);
              border-radius: 50%;
              width: 32rpx;
              height: 32rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              opacity: 0;
              transition: opacity 0.3s ease;
            }
            
            &:hover .captcha-refresh {
              opacity: 1;
            }
          }
        }
      }
    }
    
    .button-group {
      margin-top: 50rpx;
      display: flex;
      gap: 20rpx;
      
      .login-button {
        flex: 1;
        height: 88rpx;
        background: linear-gradient(135deg, #007aff 0%, #0056cc 100%);
        border: none;
        border-radius: 44rpx;
        color: #ffffff;
        font-size: 28rpx;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.3);
        transition: all 0.3s ease;
        
        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.3);
        }
        
        &:disabled {
          background: #cccccc;
          box-shadow: none;
        }
      }
      
      .wechat-login-button {
        flex: 1;
        height: 88rpx;
        background: linear-gradient(135deg, #07c160 0%, #06a85b 100%);
        border: none;
        border-radius: 44rpx;
        color: #ffffff;
        font-size: 26rpx;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 8rpx 24rpx rgba(7, 193, 96, 0.3);
        transition: all 0.3s ease;
        
        .wechat-icon {
          margin-right: 8rpx;
        }
        
        &:active {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
        }
        
        &:disabled {
          background: #cccccc;
          box-shadow: none;
        }
      }
    }
    
    
    .options-section {
      margin-top: 40rpx;
      text-align: center;
      
      .register-link {
        .link-text {
          font-size: 26rpx;
          color: #666666;
        }
        
        .link-button {
          font-size: 26rpx;
          color: #007aff;
          font-weight: 600;
          margin-left: 8rpx;
          cursor: pointer;
          
          &:active {
            opacity: 0.8;
          }
        }
      }
    }
  }
}

.agreement-section {
  text-align: center;
  
  .agreement-text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.8);
  }
  
  .agreement-link {
    font-size: 24rpx;
    color: #ffffff;
    text-decoration: underline;
    margin: 0 4rpx;
    cursor: pointer;
    
    &:active {
      opacity: 0.8;
    }
  }
}

// 绑定弹窗样式
.bind-popup {
  width: 600rpx;
  background: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  
  .bind-popup-header {
    padding: 40rpx 40rpx 20rpx;
    text-align: center;
    border-bottom: 1rpx solid #f0f0f0;
    
    .bind-popup-title {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 8rpx;
    }
    
    .bind-popup-subtitle {
      display: block;
      font-size: 24rpx;
      color: #666666;
    }
  }
  
  .bind-popup-content {
    padding: 40rpx;
    
    .wechat-user-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 40rpx;
      
      .wechat-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-bottom: 16rpx;
      }
      
      .wechat-nickname {
        font-size: 28rpx;
        color: #333333;
        font-weight: 600;
      }
    }
    
    .bind-input-group {
      margin-bottom: 40rpx;
      
      .bind-input-wrapper {
        position: relative;
        background: #f8f9fa;
        border-radius: 20rpx;
        border: 2rpx solid transparent;
        transition: all 0.3s ease;
        
        &:focus-within {
          background: #ffffff;
          border-color: #007aff;
          box-shadow: 0 0 0 6rpx rgba(0, 122, 255, 0.1);
        }
        
        .bind-input-icon {
          position: absolute;
          left: 24rpx;
          top: 50%;
          transform: translateY(-50%);
          z-index: 1;
        }
        
        .bind-input {
          width: 100%;
          height: 88rpx;
          padding: 0 24rpx 0 72rpx;
          font-size: 28rpx;
          color: #333333;
          background: transparent;
          border: none;
          outline: none;
          
          &::placeholder {
            color: #999999;
          }
        }
      }
    }
    
    .bind-button-group {
      display: flex;
      gap: 20rpx;
      
      .bind-cancel-button {
        flex: 1;
        height: 80rpx;
        background: #f5f5f5;
        border: none;
        border-radius: 40rpx;
        color: #666666;
        font-size: 28rpx;
        
        &:active {
          opacity: 0.8;
        }
      }
      
      .bind-confirm-button {
        flex: 1;
        height: 80rpx;
        background: linear-gradient(135deg, #007aff 0%, #0056cc 100%);
        border: none;
        border-radius: 40rpx;
        color: #ffffff;
        font-size: 28rpx;
        font-weight: 600;
        
        &:active {
          opacity: 0.8;
        }
        
        &:disabled {
          background: #cccccc;
        }
      }
    }
  }
}

// 解绑弹窗样式
.unbind-popup {
  width: 560rpx;
  background: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  
  .unbind-popup-header {
    padding: 40rpx 40rpx 20rpx;
    text-align: center;
    border-bottom: 1rpx solid #f0f0f0;
    
    .unbind-popup-title {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }
  }
  
  .unbind-popup-content {
    padding: 40rpx;
    
    .unbind-message {
      font-size: 28rpx;
      color: #666666;
      line-height: 1.6;
      text-align: center;
      margin-bottom: 40rpx;
    }
    
    .unbind-button-group {
      display: flex;
      gap: 20rpx;
      
      .unbind-cancel-button {
        flex: 1;
        height: 80rpx;
        background: #f5f5f5;
        border: none;
        border-radius: 40rpx;
        color: #666666;
        font-size: 28rpx;
        
        &:active {
          opacity: 0.8;
        }
      }
      
      .unbind-confirm-button {
        flex: 1;
        height: 80rpx;
        background: linear-gradient(135deg, #ff4757 0%, #ff3742 100%);
        border: none;
        border-radius: 40rpx;
        color: #ffffff;
        font-size: 28rpx;
        font-weight: 600;
        
        &:active {
          opacity: 0.8;
        }
        
        &:disabled {
          background: #cccccc;
        }
      }
    }
  }
}
</style>
